﻿#region Copyrigth and License
/*==============================================================================
 *  Copyright (c) cndotnet.org Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.cndotnet.org/ucenter
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.UI;
using UCenter.BusinessContract;
using UCenter.BusinessContract.Enumeration;
using UCenter.ContactService;
using UCenter.ContactService.LiveID;
using UCenter.ContactService.QQ;
using UCenter.Core.Service;
using UCenter.Core.Web;
using UCenter.Services;
using UCenter.TemplateEngine;
using UCenter.PluginFramework;
using UCenter.ServiceContract;

namespace UCenter.Controllers {
    [HandleError]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class FriendController : BaseController 
    {
        private FriendService service = new FriendService();

        public ActionResult Index()
        {
            ViewData["Title"] = "我的好友";

            ////List<FriendContract> friends = service.GetFriends(ContextService.Current.User.ID);

            //if (friends != null)
            //{
            //    ViewData["Friends"] = friends;
            //}

            return View();
        }

        public ActionResult Group() {
            ViewData["Title"] = "好友管理";
            return View();
        }

        #region Status
        public ActionResult Status() {
            ViewData["Title"] = "好友状态";
            return View();
        }
        public string GetFriendsStatus() {
            int currentUserID = ContextService.Current.User.ID;
            var users = service.GetFriendsWhoHasStatusSetting(currentUserID, "");
            return users.ToJSON<AccountContract>();
        }
        #endregion

        public ActionResult Visitor() {
            ViewData["Title"] = "谁来看过我";
            return View();
        }

        public ActionResult Visited() {
            ViewData["Title"] = "我去看过谁";
            return View();
        }

        #region Online
        public ActionResult Online() {
            return View();
        }
        public string GetOnlineFriends() {
            int currentUserID = ContextService.Current.User.ID;
            var users = service.GetOnLineFriendsByUserID(currentUserID, "");
            return users.ToJSON<AccountContract>();
        }
        #endregion

        #region Find
        /// <summary>
        /// Find
        /// </summary>
        /// <returns></returns>        
        public ActionResult Find()
        {
            Invite();
            return View();
        }

        public string FindByEmail(string exactEmail)
        {
            exactEmail = exactEmail.Trim();
            var account = new AccountService().GetAccountByEmail(exactEmail,false);
            int currentUserID = ContextService.Current.User.ID;
            UContractCollection mc = new UContractCollection();
            List<AccountContract> accounts = new List<AccountContract>();
            if (accounts != null)
            {
                accounts.Add(account);
            }
            var friends = new FriendService().GetFriendsByUserID(currentUserID,"");
            mc.RemoveAll(delegate(UContract u) { return accounts.Exists(delegate(AccountContract ac) { return ac.Email == u.Email; }) || u.Email == ContextService.Current.User.Email; });
            accounts.RemoveAll(delegate(AccountContract ac) { return ac.ID == currentUserID || friends.Exists(delegate(AccountContract fc) { return ac.ID == fc.ID; }); });
            InviteContract ir = new InviteContract();
            ir.ExistAccounts = accounts;
            ir.ContractList = mc;
            string returnStr = Core.Common.JsonFormaterUtils.Serialize<InviteContract>(ir);
            return returnStr;
        }
        /// <summary>
        /// find by truename
        /// </summary>
        /// <param name="trueName">truename</param>
        /// <returns></returns>
        public string FindByName(string trueName)
        {
            trueName = trueName.Trim();
            var accounts = new AccountService().GetAccountsByName(trueName,false);
            int currentUserID = ContextService.Current.User.ID;
            UContractCollection mc = new UContractCollection();
            var friends = new FriendService().GetFriendsByUserID(currentUserID,"");
            mc.RemoveAll(delegate(UContract u) { return accounts.Exists(delegate(AccountContract ac) { return ac.Email == u.Email; }) || u.Email == ContextService.Current.User.Email; });
            accounts.RemoveAll(delegate(AccountContract ac) { return ac.ID==currentUserID||friends.Exists(delegate(AccountContract fc) { return ac.ID == fc.ID; }); });
            InviteContract ir = new InviteContract();
            ir.ExistAccounts = accounts;
            ir.ContractList = mc;
            string returnStr = Core.Common.JsonFormaterUtils.Serialize<InviteContract>(ir);
            return returnStr;
        }

        #endregion

        #region Invite
        public ActionResult Invite() {
            ViewData["Title"] = "邀请好友";
            List<string> list = new List<string>() {
                "126.com",
                "163.com",
                "vip.163.com",
                "sohu.com",
                "vip.sohu.com",
                "sina.com.cn",
                "vip.sina.com",
                "yahoo.com",
                "ymail.com",
                "rocketmail.com",
                "yahoo.cn",
                "yahoo.com.cn",
                "tom.com",
                "21cn.com",
                "hotmail.com",
                "live.cn",
                "live.com",
                "msn.com",
                "gmail.com"
            };
            SelectList mails = new SelectList(list);
            ViewData["EmailSystems"] = mails;

            string ts = "";
            ts = new QQService().GetTs();
            ViewData["ts"] = ts;

            //string AuthCookie = WebConfigurationManager.AppSettings["delAuthCookie"];
            //DateTime ExpireCookie = DateTime.Now.AddYears(-10);
            //DateTime PersistCookie = DateTime.Now.AddYears(10);
            //string Offers = "Contacts.View";
            //string ConsentUrl;
            ////初始化WindowsLiveLogin
            //WindowsLiveLogin wll = new WindowsLiveLogin(true);
            //wll.ReturnUrl = HttpContext.Request.Url.ToString();
            //WindowsLiveLogin.ConsentToken Token = null;
            //ConsentUrl = wll.GetConsentUrl(Offers);
            //ViewData["ConsentUrl"] = ConsentUrl;
            //var req = ControllerContext.HttpContext.Request;
            //HttpCookie authCookie = req.Cookies[AuthCookie];

            //if (authCookie != null) {
            //    string t = authCookie.Value;
            //    Token = wll.ProcessConsentToken(t);


            //    if ((Token != null) && !Token.IsValid()) {
            //        Token = null;
            //    }
            //    else {

            //    }
            //}
            //{
            //    var res = ControllerContext.HttpContext.Response;
            //    authCookie = new HttpCookie(AuthCookie);

            //    string action = req["action"];

            //    if (action == "delauth") {

            //        Token = wll.ProcessConsent(req.Form);
            //        if (Token != null) {
            //            authCookie.Value = Token.Token;
            //            authCookie.Expires = PersistCookie;
            //        }
            //        else {
            //            authCookie.Expires = ExpireCookie;
            //        }

            //        res.Cookies.Add(authCookie);
            //    }
            //}
            //ViewData["Token"] = Token;


            //获取我的好友分组
            int currentUserID = ContextService.Current.User.ID;

            List<FriendGroupContract> groups = LoadService<IFriendGroupService>().GetGroupsByUserId(currentUserID);

            SelectList sList = new SelectList(groups, "ID", "GroupName");
            ViewData["MyFriendGroup"] = sList;
            return View();
        }    

        public string GetLiveContracts() {
            //ContractServiceUtil csu = new ContractServiceUtil(ContractType.Live);
            
            //var ucc = csu.GetContracts("", "", "");

            UContractCollection ucc = PlugInManager.CurrentHost.Extensions["ContactFromLiveID"].Execute()["Emails"] as UContractCollection;

            List<string> emails = new List<string>();
            foreach (var c in ucc) {
                emails.Add(c.Email);
            }
            int currentUserID = ContextService.Current.User.ID;
            var accounts = new AccountService().GetAccountsByContracts(currentUserID,ContractTypeEnum.Live, emails);
            var friends = service.GetFriendsByUserID(currentUserID,"");
            ucc.RemoveAll(delegate(UContract u) { return accounts.Exists(delegate(AccountContract ac) { return ac.MSN == u.Email; }) || u.Email == ContextService.Current.User.MSN; });
            accounts.RemoveAll(delegate(AccountContract ac) { return friends.Exists(delegate(AccountContract fc) { return ac.ID == fc.ID; }); });
            InviteContract ir = new InviteContract();
            ir.ExistAccounts = accounts;
            ir.ContractList = ucc;
            string returnStr = Core.Common.JsonFormaterUtils.Serialize<InviteContract>(ir);
            return returnStr;
        }
        public string GetNewQQVerifyCodeImg() {
            VerifyCode vc = QQService.GetVerifyCode("http://ptlogin2.qq.com/getimage?aid=23000101&", "/vc");
            return vc.ToJson();
        }
   
        [AcceptVerbs("POST"), ActionName("InviteQQ")]
        public string GetQQContracts(string uid, string p, string verifyCode, string ts, string cookies) {
            try {
                CookieContainer cc = new CookieContainer();
                var ucc = new ContractServiceUtil(ts, cookies).GetContracts(uid, p, verifyCode);
                List<string> qqs = new List<string>();
                foreach (var c in ucc) {
                    qqs.Add(c.Email.Replace("@qq.com", ""));
                }                
                int currentUserID = ContextService.Current.User.ID;
                var accounts = new AccountService().GetAccountsByContracts(currentUserID,ContractTypeEnum.QQ, qqs);
                var friends = service.GetFriendsByUserID(currentUserID,"");
                ucc.RemoveAll(delegate(UContract u) { return accounts.Exists(delegate(AccountContract ac) { return ac.QQ == u.Email.Replace("@qq.com", ""); }) || u.Email.Replace("@qq.com", "") == ContextService.Current.User.QQ; });
                accounts.RemoveAll(delegate(AccountContract ac) { return friends.Exists(delegate(AccountContract fc) { return ac.ID == fc.ID; }); });
                InviteContract ir = new InviteContract();
                ir.ExistAccounts = accounts;
                ir.ContractList = ucc;
                string returnStr = Core.Common.JsonFormaterUtils.Serialize<InviteContract>(ir);
                return returnStr;
            }
            catch {
                return "";
            }
        }  

        [AcceptVerbs("POST"), ActionName("InviteEmail")]
        public string GetEmailContracts(string EmailSystems, string uid, string pwd) {
            var mc = new ContactService.ContractServiceUtil(ContractType.Email).GetContracts(string.Concat(uid + "@", EmailSystems), pwd, "");
            List<string> emails = new List<string>();
            foreach (var c in mc) {
                emails.Add(c.Email);
            }
            int currentUserID = ContextService.Current.User.ID;
            var accounts = new AccountService().GetAccountsByContracts(currentUserID,ContractTypeEnum.Email, emails);
            var friends = service.GetFriendsByUserID(currentUserID,"");
            mc.RemoveAll(delegate(UContract u) { return accounts.Exists(delegate(AccountContract ac) { return ac.Email == u.Email; }) || u.Email == ContextService.Current.User.Email; });
            accounts.RemoveAll(delegate(AccountContract ac) { return friends.Exists(delegate(AccountContract fc) { return ac.ID == fc.ID; }); });
            InviteContract ir = new InviteContract();
            ir.ExistAccounts = accounts;
            ir.ContractList = mc;
            string returnStr = Core.Common.JsonFormaterUtils.Serialize<InviteContract>(ir);
            return returnStr;
        }
        public string AddFriend(string postData,int groupID) {
            var ac = UCenter.Core.Common.JsonFormaterUtils.Deserialize<List<AccountContract>>(postData, Encoding.GetEncoding("utf-8"));
            int currentUserID = ContextService.Current.User.ID;

            foreach (var a in ac) 
            {
                TemplateContract msgTemplate = new TemplateContract("AddFriendMessageTemplate");
                msgTemplate.Parameters.Add("FriendUserID", ContextService.Current.User.ID.ToString());
                msgTemplate.Parameters.Add("FromUserName", ContextService.Current.User.TrueName);

                new MessageService().InsertMessage(ContextService.Current.User, a.ID,msgTemplate,MessageType.AddFriend);
                service.AddFriend(currentUserID, a.ID,groupID);
            }
            return "success";
        }
        public string SendInvite(string postData) {
            var ucc = Core.Common.JsonFormaterUtils.Deserialize<List<UContract>>(postData, Encoding.GetEncoding("utf-8"));
            foreach (var c in ucc) {
                int currentUserID = ContextService.Current.User.ID;
                service.Invite(currentUserID, c.Name, c.Email);
            }
            return "success";
        }
        #endregion

        #region Group
        public string GetGroups()
        {
            int currentUserID = ContextService.Current.User.ID;
            List<FriendGroupContract> groups = LoadService<IFriendGroupService>().GetGroupsByUserId(currentUserID);
            return groups.ToJSON<FriendGroupContract>();
        }

        public string GetFriends(int groupID)
        {
            int currentUserID = ContextService.Current.User.ID;
            var users = service.GetFriendsByID(groupID);
            return users.ToJSON<AccountContract>();
        }

        public string GetFriendsByUserID(string kw)
        {
            int currentUserID = ContextService.Current.User.ID;
            var users = service.GetFriendsByUserID(currentUserID, kw);
            return users.ToJSON<AccountContract>();
        }

        public void AddGroup(string newGroupName) {
            int currentUserID = ContextService.Current.User.ID;
            IFriendGroupService groupService = LoadService<IFriendGroupService>();
            groupService.InsertGroup(
                    new FriendGroupContract { UserID = currentUserID, GroupName = newGroupName }
                );
        }

        public void DeleteGroup(int groupID) {
            new FriendGroupService().DeleteGroup(groupID);
        }

        public void DeleteFriend(int friendID)
        {
            int currentUserID = ContextService.Current.User.ID;
            service.Delete(currentUserID, friendID);
        }

        public void UpdateGroup(int groupID, string editGroupName)
        {
            IFriendGroupService groupService = LoadService<IFriendGroupService>();
            groupService.UpdateGroup(
                    new FriendGroupContract { ID = groupID, GroupName = editGroupName }
                );
        }

        public void UpdateFriendGroup(int friendID, int newGroupID)
        {
            int currentUserID = ContextService.Current.User.ID;
            service.UpdateGroupSetting(currentUserID, friendID,newGroupID);
        }
        #endregion
    }
}
